/*
 * @Author: MrRice
 * @Date: 2024-07-18 22:43:31
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-07-18 23:58:57
 * @FilePath: /workerCreator/examples/worker/index.js
 * @Description:
 * -----小舟从此逝，江海寄余生----
 * Copyright (c) 2024 by 米大饭, All Rights Reserved.
 */
import WorkerCreator from 'workercreator';

import now from 'performance-now';
import WorkScript from './computer.work';

const computerTime = (callback, endCallback) => {
  let start = now();
  // 你的代码
  console.log('开始计算');

  if (typeof callback === 'function') {
    callback();
  }
  let end = now();
  const result = end - start;
  console.log(`myFunction 执行时间: ${result} 毫秒`);
  if (typeof endCallback === 'function') {
    endCallback(result);
  }
};

//js计算斐波那契数列
function fibonacci(n) {
  if (n <= 1) {
    return n;
  }
  return fibonacci(n - 1) + fibonacci(n - 2);
}

document.getElementById('jscomputer').onclick = () => {
  computerTime(
    () => {
      const res = fibonacci(44);
      console.log(res);
      document.getElementById('jsresult').innerHTML = `结果: ${res}`;
    },
    (res) => {
      document.getElementById('jsresulttime').innerHTML = `计算时间: ${res} 毫秒`;
    },
  );
};

const work = new WorkerCreator();

document.getElementById('workercomputer').onclick = () => {
  let start = now();
  work.addWorker(WorkScript, 44, (res) => {
    console.log(res, '计算结果');
    let end = now();
    const result = end - start;
    console.log(`myFunction 执行时间: ${result} 毫秒`);
    document.getElementById('workerresult').innerHTML = `计算结果: ${res}`;
    document.getElementById('workerresulttime').innerHTML = `计算时间: ${result} 毫秒`;
  });
};
